package org.example;

import org.example.bean.Production;
import org.example.bean.Token;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;


class Main {
    public static void main(String[] args) throws FileNotFoundException {
        // 读取源程序
//        String sourceCode ="(a)";
        System.out.println("待分析句子");
        String sourceCode ="a+10*b-c/4;";
        System.out.println(sourceCode);
//        String sourceCode ="(a+a-(a*a)/a)/a-a*a/a+a-a;";


        // 进行词法分析
        System.out.println("进行分词");
        char[] src=sourceCode.toCharArray();
        TokensAnalyzer tokensAnalyzer = new TokensAnalyzer();
        List<Token> tokens = tokensAnalyzer.getTokens(src);
        for (Token token : tokens) {
            System.out.printf("(%s, '%s')\n", token.type, token.value);
        }

        //从文件中读取文法

        System.out.println("匹配文法");
        try {
            FileReader file = new FileReader("src/main/resources/grammar2.txt");
            BufferedReader bf = new BufferedReader(file);
            String temp = null;
            while ((temp = bf.readLine()) != null) {
                System.out.println(temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        List<Production> productionList = GrammarParser.parseGrammar(new File("src/main/resources/grammar2.txt"));
        System.out.println("消除左递归");
        GrammarParser.eliminateLeftRecursion(productionList);
        GrammarParser grammarParser = new GrammarParser();
        grammarParser.setProductions(productionList);
        System.out.println("计算first集");
        grammarParser.getAllFirst(productionList);
        System.out.println("计算follow集");
        grammarParser.getAllFollow(productionList);
        grammarParser.initParseTable(productionList);
//        grammarParser.setTokenList(tokens);
//        tokens.remove(tokens.size() - 2);
//        System.out.println("开始分析并推导");
//        System.out.print("E");
//        grammarParser.match(tokens, "E");
//        if (tokens.size() == 1 && ((Token)tokens.get(0)).type == TokenType.END) {
//            System.out.println("匹配完成");
//        }

    }
}